# Create your views here.
from rest_framework import serializers
from .models import User,Order,State
from .choices import SAMPLE_TYPE

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username','email','is_superuser']

class StateSerializer(serializers.ModelSerializer):
    operator =  UserSerializer(required=False)
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, required=False)

    class Meta:
        model = State
        fields = '__all__'

    def create(self, validated_data):
        order = validated_data.pop("order", None)
        state = State.objects.create(order=order)
        self.update(state,validated_data)
        return state

    def update(self, instance, validated_data):
        operator = validated_data.pop("user", None)
        if operator is None :
            operator = self.context["request"].user
        instance.__dict__.update(**validated_data)
        instance.operator=operator
        instance.save()
        return instance


class OrderSerializer(serializers.HyperlinkedModelSerializer):
    seller = UserSerializer(required=False)
    state = StateSerializer(read_only=True)
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),write_only=True,required=False)
    sample_type = serializers.MultipleChoiceField(choices=SAMPLE_TYPE)

    class Meta:
        model = Order
        fields = '__all__'

    def create(self, validated_data):
        seller = validated_data.pop("user", None)
        order = Order(**validated_data)
        if seller is None :
            seller = self.context["request"].user
        order.seller = seller
        order.save()
        State.objects.create(order = order, operator=seller)
        return order